#   定时任务路由

from flask import (
    Blueprint,
    request,
    g,
    current_app
)

from exit import db
from apps.api.models import User, UserRecord
from apps.common.models import *
from apps.mall.models import *
from decimal import Decimal
from datetime import datetime, date, timedelta
from sqlalchemy import or_, func
from utils import restful, api_util, redis_cach, common_util
import random
import subprocess
from shortuuid import uuid


bp = Blueprint("task", __name__, url_prefix="/task")


@bp.route('/order_confirm_task/')   # 定时任务确认收货
def order_confirm_task():
    d_time = (datetime.now() - timedelta(days=15))
    buy_order = BuyOrder.query.filter(
        BuyOrder.status == 2,
        BuyOrder.create_time < d_time
    ).all()
    count = 0
    for i in buy_order:
        i.status = 3
        i.update_time3 = datetime.now()
        count += 1
    db.session.commit()
    return '成功{}条'.format(count)


@bp.route('/del_buy_order/')
def del_buy_order():
    buy_order = BuyOrder.query.filter_by(status=0).all()
    for i in buy_order:
        i.status = 2
        user = User.query.filter_by(id=i.user_id).first()
        if i.t_type == 2:  # 返还批次数量
            i.bath.s_num_sell += i.num
            i.bath.s_num += i.num
        elif i.t_type == 1:
            user.income += i.surplus_price
            api_util.user_record(user_id=user.id, r_label=1, r_type=4, r_state=1, num=i.surplus_price, r_wallet=1)

            user.income += i.surplus_fee
            api_util.user_record(user_id=user.id, r_label=2, r_type=3, r_state=1, num=i.surplus_fee, r_wallet=1)
        db.session.commit()


@bp.route('/goods_add/')
def goods_add():
    day_week = datetime.now().weekday()
    if day_week in [6, 0]:
        return '今天是周{}！'.format(day_week+1)
    today = date.today() + timedelta(days=-1)
    work_day = common_util.work_day(today)
    if work_day is False:
        return '今天是节假日！周{}'.format(day_week+1)

    goods = db.session.query(Goods).filter_by(id=80).first()
    # y_price = goods.price
    buy_deal = BuyDeal.query.filter_by(deal_type=1).order_by(BuyDeal.create_time.desc()).first()

    goods.price = buy_deal.deal_price

    # 插入记录
    record = HistoryPrice(goods_id='80', price=goods.price, y_price=goods.price, create_time=date.today())
    db.session.add(record)

    buy_num = int(GlobalParams.get_params(2))
    sell_num = int(GlobalParams.get_params(4))

    db.session.execute("update c_user set today_buy_num=today_buy_num-{} where today_buy_num>0;".format(buy_num))
    db.session.execute("update c_user set today_sell_num=today_sell_num-{} where today_sell_num>0;".format(sell_num))
    db.session.execute("update c_user set today_buy_num=0 where today_buy_num<0")
    db.session.execute("update c_user set today_sell_num=0 where today_sell_num<0")

    db.session.commit()
    return '成功'


@bp.route('/reset_num_price/')
def reset_num_price():
    global_num = GlobalParams.query.filter_by(g_type=6).first()
    global_price = GlobalParams.query.filter_by(g_type=7).first()
    global_num.global_params = 0
    global_price.global_params = 0
    sql = 'UPDATE c_mall_buy_deal set tn_day=tn_day-1 where tn_day>0'
    db.session.execute(sql)
    db.session.commit()
    return '成功'


@bp.route('/select_buy_deal/')
def select_buy_deal():
    buy_sell = db.session.query(func.sum(BuyDeal.deal_money)).filter(
        BuyDeal.goods_id == '80', BuyDeal.create_time >= date.today(), BuyDeal.deal_type == 1
    ).scalar()
    buy_sell_price = buy_sell or 0

    buy_sell_num = db.session.query(func.sum(BuyDeal.deal_num)).filter(
        BuyDeal.goods_id == '80', BuyDeal.create_time >= date.today(), BuyDeal.deal_type == 1
    ).scalar()
    buy_sell_num = buy_sell_num or 0
    redis_cach.set_last('buy_sell_price', str(buy_sell_price))
    redis_cach.set_last('buy_sell_num', str(buy_sell_num))

    num = redis_cach.get('buy_sell_num')
    price = redis_cach.get('buy_sell_price')
    return '创建成功! 当前数量：{}, 当前价格{}, 时间：{}'.format(num, price, datetime.now())


@bp.route('/buy_sell_task/')     # 买和卖缓存
def buy_sell_task():
    buy_order = db.session.query(BuyOrder.surplus_num, BuyOrder.price).filter_by(t_type=1, status=0).order_by(BuyOrder.price.desc()).limit(5)
    buy_lists = list()
    for i in buy_order:
        order_info = dict()
        order_info['surplus_num'] = i.surplus_num
        order_info['price'] = i.price
        buy_lists.append(str(order_info))

    sell_lists = list()
    sell_order = db.session.query(BuyOrder.surplus_num, BuyOrder.price).filter_by(t_type=2, status=0).order_by(BuyOrder.price).limit(5)
    for j in sell_order:
        order_info = dict()
        order_info['surplus_num'] = j.surplus_num
        order_info['price'] = j.price
        sell_lists.append(str(order_info))

    try:
        redis_cach.pipe.multi()     # 开始事务

        # 删除列表
        redis_cach.pipe.delete('buy_list')
        redis_cach.pipe.delete('sell_list')
        if len(buy_lists) > 0:
            redis_cach.pipe.rpush('buy_list', *buy_lists)
        if len(sell_lists) > 0:
            redis_cach.pipe.rpush('sell_list', *sell_lists)

        redis_cach.pipe.execute()   # 提交事务
    except Exception as e:
        print(e)

    # get_buy_list = redis_cach.cache.lrange('buy_list', 0, -1)
    # get_sell_list = redis_cach.cache.lrange('sell_list', 0, -1)
    # get_buy_list = [eval(i) for i in get_buy_list]
    # get_sell_list = [eval(i) for i in get_sell_list]

    return '创建成功! 时间：{}'.format(datetime.now())


@bp.route('/transfer_order_count/')
def transfer_order_count():
    from datetime import datetime, timedelta

    # 冻结转让费
    y_date = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')
    params = db.session.query(GlobalParams).filter(GlobalParams.g_type == 11).first().global_params

    order_num = db.session.query(db.func.sum(TransferOrder.num).label('num')).filter(
        TransferOrder.t_type == 2, TransferOrder.status == 1,
        TransferOrder.update_time.like("{}%".format(y_date))).first().num or 0

    total_dj = params * order_num

    # print('冻结转让费：', total_dj)

    # 冻结释放费
    total_release = db.session.query(db.func.sum(UserRecord.num).label('num')).filter(
        UserRecord.r_label == 1, UserRecord.r_type == 9,
        UserRecord.create_time.like("{}%".format(y_date))).first().num or 0

    # print('冻结释放费：', total_release)

    main_user = db.session.query(User).filter_by(id='bXZ4cXumWF76gchBPomzZP').with_for_update().first()

    if total_dj > 0:
        main_user.income += total_dj
        api_util.user_record(user_id=main_user.id,  r_label=1, r_type=12,num=total_dj, r_state=1, r_wallet=1)

    if total_release > 0:
        main_user.income += total_release
        api_util.user_record(user_id=main_user.id, r_label=1, r_type=13, num=total_release, r_state=1, r_wallet=1)

    db.session.commit()

    return '冻结转让费<{}> 冻结释放费<{}> 时间：{}'.format(total_dj, total_release, datetime.now())

